package execution;

import java.io.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import static utils.Constants.*;

/**
 * @author Eduardo Rosales
 * Responsible for executing local commands
 */
public class LocalProcessExecutor {

    private static String outputs;
    private static String command;

    /**
     * Responsible for executing local commands without output
     * @param inCommand
     * @return
     */
    public boolean executeCommand(String inCommand) {
        boolean successfulExecution = true;
        outputs = new String();
        command = inCommand;
        try {
            Runtime.getRuntime().exec(command);
        } catch (IOException ex) {
            outputs = "Error executing command: " + ex.toString() + "\n";
            System.out.println(outputs);
            successfulExecution = false;
        }
        return successfulExecution;
    }

    /**
     * Responsible for executing local commands in a specific directory
     * @param inCommand
     * @param directory
     * @return
     * @throws IOException
     */
    public boolean executeCommandDiretory(String inCommand, String directory) throws IOException {
        File dir = new File(directory);
        boolean successfulExecution = true;
        outputs = new String();
        command = inCommand;
        try {
            Runtime.getRuntime().exec(command, null, dir);
        } catch (IOException ex) {
            outputs =ERROR_MESSAGE +"executing command: " + ex.toString() + "\n";
            System.out.println(outputs);
            successfulExecution = false;
        }
        return successfulExecution;
    }

    /**
     * Responsible for executing local commands with outputs
     * @param inCommand
     * @param repLine
     * @return
     */
    public String executeCommandOutput(String inCommand, boolean repLine) {
        String execute = "";
        outputs = new String();
        command = inCommand;
        try {
            Process p = Runtime.getRuntime().exec(command);
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                outputs += line + "\n";
                if (repLine) {
                    line = in.readLine();
                }
            }
        } catch (IOException ex) {
            execute = ERROR_MESSAGE + "executing command " + inCommand + " : " + ex.getMessage() + "\nthe command output was: " + outputs;
            System.out.println(execute);
            return execute;
        }
        return outputs;
    }
}
